let dao = require('../database/dao'),
  logger = require('../helper/logger'),
  tagLogger = new logger.TagLogger('BANNER_MODEL'),
  errorCode = require('../../conf/errorCode'),
  commonModel = require('./commonModel'),
  util = require('../helper/util'),
  _ = require('lodash');

let {
  genUpdateCallback,
  genInsertCallback,
  genUpdateRslt,
  genUpdateBatchRslt,
  genUpdateBatchCallback,
  genSelectCallback,
  genPagination,
  genInertRslt,
} = commonModel;

//创建运营位数据
exports.add = function(tableName, bannerObj, callback) {
  dao.executeMultipleQuery(
    [
      {
        str: `select * from ${tableName} where nextId=-1 and status >= 0`,
        param: [tableName],
      },
      {
        str: `select max(id) as id from ${tableName}`,
        param: [tableName],
      },
    ],
    function(err, rel) {
      if (err) {
        return callback(err);
      }
      let existRecord = rel[0].length > 0 ? true : false;
      if (!existRecord) {
        bannerObj.prevId = -1;
        bannerObj.nextId = -1;
        return dao.insert(tableName, bannerObj, genInsertCallback(callback));
      }

      let query1 = {
        str: `update ${tableName} set nextId=? where id =?`,
        param: [rel[1][0].id + 1, rel[0][0].id],
      };
      bannerObj.prevId = rel[0][0].id;
      bannerObj.nextId = -1;
      let query2 = {
        str: `insert into ?? set ?`,
        param: [tableName, bannerObj],
      };
      let queryArr = [query1, query2];
      dao.queryBatch(queryArr, (err, rslts) => {
        if (err == null) callback(null, rslts);
        else callback(err, null);
      });
    },
  );

  //dao.all(`select * from ${tableName} where nextId=-1`, [], (err, _rel) => {
  //let existRecord = _rel.length > 0 ? true : false;

  //if (!existRecord) {
  //bannerObj.prevId = -1;
  //bannerObj.nextId = -1;
  //return dao.insert(tableName, bannerObj, genInsertCallback(callback));
  //}

  //let query1 = {
  //str: `update ${tableName} set nextId=? where id =?`,
  //param: [_rel[0].id + 1, _rel[0].id],
  //};
  //let query2 = {
  //str: `insert into ? set ?`,
  //param: [tableName, bannerObj],
  //};
  //let queryArr = [query1, query2];
  //console.log(queryArr);
  //dao.queryBatch(queryArr, (err, rslts) => {
  //if (err == null)
  //callback(null, genPagination(rslts[0], page, size, rslts[1][0].count));
  //else callback(err, null);
  //});
  //});
};

//获取运营位列表
exports.getOperateByPage = function(tableName, flag, page, size, callback) {
  //flag=1 当前使用 flag=0 过期
  let [offset, limit] = util.ps2ol(page, size),
    //fromJoinWhere = `FROM ${tableName} where status >= 0 and ${flag == 1
    fromJoinWhere = `FROM ${tableName} where ${flag == 1
      ? 'status>=0'
      : 'status<0'}`;
  //fromJoinWhere = `FROM ${tableName} where status >= 0 and ${flag == 1
  //? 'TO_DAYS(validateDate) >= TO_DAYS(NOW())'
  //: 'TO_DAYS(validateDate) < TO_DAYS(NOW())'}`;
  let postQuery = {
    str: `SELECT * ${fromJoinWhere} LIMIT ?,?`,
    param: [offset, limit],
  };
  let countQuery = {
    str: `SELECT count(1) as count ${fromJoinWhere}`,
    param: [],
  };
  let queryArr = [postQuery, countQuery];
  dao.queryBatch(queryArr, (err, rslts) => {
    if (err == null)
      callback(null, genPagination(rslts[0], page, size, rslts[1][0].count));
    else callback(err, null);
  });
};

//删除运营位-支持批量删除
exports.deleteOperateByIds = function(tableName, ids, callback) {
  dao.deleteBatch(tableName, ids, callback);
};

//更新运营位
exports.updateData = async function(tableName, operateId, data, callback) {
  if (new Date(data.validateDate).getTime() < Date.now()) {
    let modifyDetail = await util.promiseify(
      dao.all,
    )(`select * from ${tableName} where id=?`, [operateId]);
    let prevId = modifyDetail[0].prevId,
      nextId = modifyDetail[0].nextId;
    //过期
    let query1 = {
        str: `update ${tableName} set status=-1 where id=?`,
        param: [operateId],
      },
      query2 = {
        str: `update ${tableName} set nextId=? where id=?`,
        param: [nextId, prevId],
      },
      query3 = {
        str: `update ${tableName} set prevId=? where id=?`,
        param: [prevId, nextId],
      },
      queryArr = [];

    queryArr.push(query1);

    if (prevId != -1) {
      queryArr.push(query2);
    }
    if (nextId != -1) {
      queryArr.push(query3);
    }
    dao.queryBatch(queryArr, callback);
  } else {
    let str = `UPDATE ${tableName} SET `,
      k = [],
      v = [];
    _.forEach(data, function(value, key) {
      k.push(key + ' = ?');
      v.push(value);
    });
    v.push(operateId);
    str = str + k.join(',');
    str = str + ' where id = ? and status = 0';
    dao.all(str, v, callback);
  }
};

function promiseify(method) {
  return function(ctx) {
    let args = Array.prototype.slice.call(arguments);

    return new Promise((resolve, reject) => {
      let cb = function(err, result) {
        if (err) {
          return reject(err);
        }

        return resolve(result);
      };

      args.push(cb);
      method.apply(ctx, args);
    });
  };
}

var moveOperatePosition = (exports.moveOperatePosition = function(
  tableName,
  operateId,
  type,
  callback,
) {
  dao.all(
    `select * from ${tableName} where id=${operateId}`,
    [],
    (err, _rel) => {
      if (err || (!_rel || _rel.length < 1)) {
        return callback(err);
      }
      let {prevId, nextId} = _rel[0];

      if ((prevId == -1 && type == 'up') || (nextId == -1 && type == 'down')) {
        return callback('ccccc');
      }

      let sql =
        type == 'up'
          ? `select * from ${tableName} where id=${prevId}`
          : `select * from ${tableName} where id=${nextId}`;

      dao.all(sql, [], (err, _rel) => {
        if (err || (!_rel || _rel.length < 1)) {
          return callback(err);
        }
        let relBefore = _rel[0].prevId,
          relNext = _rel[0].nextId,
          id = _rel[0].id;

        let update1Query = {
          str: `update ${tableName} set prevId=? ,nextId=? where id=?`,
          param: [relBefore, id, operateId],
        };

        let update2Query = {
          str: `update ${tableName} set prevId=? ,nextId=? where id=?`,
          param: [operateId, nextId, id],
        };
        //下
        let update3Query = {
          str: `update ${tableName} set prevId=? where id=?`,
          param: [id, nextId],
        };
        //上
        let update4Query = {
          str: `update ${tableName} set nextId=? where id=?`,
          param: [operateId, relBefore],
        };

        let update5Query = {
          str: `update ${tableName} set prevId=? ,nextId=? where id=?`,
          param: [id, relNext, operateId],
        };

        let update6Query = {
          str: `update ${tableName} set prevId=? ,nextId=? where id=?`,
          param: [prevId, operateId, id],
        };
        //上
        let update7Query = {
          str: `update ${tableName} set nextId=? where id=?`,
          param: [id, prevId],
        };
        //下
        let update8Query = {
          str: `update ${tableName} set prevId=? where id=?`,
          param: [operateId, relNext],
        };

        let queryArr = [];
        if (type == 'up') {
          queryArr.push(update1Query, update2Query);
          if (nextId != -1) {
            queryArr.push(update3Query);
          }
          if (relBefore != -1) {
            queryArr.push(update4Query);
          }
        } else {
          queryArr.push(update5Query, update6Query);
          if (prevId != -1) {
            queryArr.push(update7Query);
          }
          if (relNext != -1) {
            queryArr.push(update8Query);
          }
        }
        //console.log(queryArr);
        dao.queryBatch(queryArr, (err, rslts) => {
          if (err == null) {
            callback(null, genInertRslt(rslts[1]));
          } else {
            callback(err, null);
          }
        });
      });
    },
  );
});
